package com.wust.modules.codegenerate.generate.util;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wanheng
 */
@Slf4j
public class ConfigurationUtil {

    public static Configuration getConfiguration(List<File> fileList, String code, String s) throws IOException {
        Configuration configuration = new Configuration();
        log.debug(" FileTemplateLoader[] size " + fileList.size());
        log.debug(" templateRootDirs templateName " + s);
        FileTemplateLoader[] fileTemplateLoaders = new FileTemplateLoader[fileList.size()];

        for(int i = 0; i < fileList.size(); ++i) {
            File file = (File) fileList.get(i);
            log.debug(" FileTemplateLoader " + file.getAbsolutePath());
            fileTemplateLoaders[i] = new FileTemplateLoader(file);
        }

        MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(fileTemplateLoaders);
        configuration.setTemplateLoader(multiTemplateLoader);
        configuration.setNumberFormat("###############");
        configuration.setBooleanFormat("true,false");
        configuration.setDefaultEncoding(code);
        return configuration;
    }


    public static String getStringWriter(String templateFile, Map<String, Object> map, Configuration configuration) {
        StringWriter stringWriter = new StringWriter();

        try {
            Template template = new Template("templateString...", new StringReader(templateFile), configuration);
            template.process(map, stringWriter);
            return stringWriter.toString();
        } catch (Exception e) {
            throw new IllegalStateException("cannot process templateString:" + templateFile + " cause:" + e, e);
        }
    }

    public static void write(Template template, Map<String, Object> map, File file, String code) throws IOException, TemplateException {
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), code));
        map.put("Format", new SimpleFormat());
        template.process(map, bufferedWriter);
        bufferedWriter.close();
    }
}
